/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * MainWindow.java
 *
 * Created on 26.05.2010, 18:03:33
 */

package it.unibz.inf.cn.gui;

import java.util.Iterator;
import java.util.Vector;

import it.unibz.inf.cn.Client;

import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPopupMenu;

/**
 *
 * @author Manfred
 */
public class MainWindow extends javax.swing.JPanel {

	
	private Client client = null;
    /**
	 * 
	 */
	private static final long serialVersionUID = 1040968691170597371L;
	/** Creates new form MainWindow */
    public MainWindow(Client c) {
    	client = c;
        initComponents();
        init();
    }
    
    private void init() {
    	
    	jTextAreaTweets.addKeyListener(new KeyListener() {
			
			@Override
			public void keyTyped(KeyEvent e) {}
			public void keyReleased(KeyEvent e) {}
			public void keyPressed(KeyEvent e) {
				if(e.getKeyCode() == KeyEvent.VK_ENTER){
					try {
						client.updateTweets();
					} catch (Exception e1) {
						e1.printStackTrace();
					}
				}	
			}
		});
    	
    	try {
			Vector<String> tweets = client.getLast100Tweets();
			Iterator<String> it = tweets.iterator();
			while(it.hasNext()){
				String text = jTextAreaTweets.getText();
				String tweet = text +"\n"+ it.next();
				jTextAreaTweets.setText(tweet);
			}
			client.startUpdating();
		} catch (Exception e) {
			e.printStackTrace();
		}
    }
    
    public void writeTweets(Vector<String> tweets){
    	Iterator<String> it = tweets.iterator();
    	jTextAreaTweets.setText("");
		while(it.hasNext()){
			String text = jTextAreaTweets.getText();
			String t = it.next();
			String tweet = text +"\n"+ t;
			jTextAreaTweets.setText(tweet);
		}
    }
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    private void initComponents() {
        java.awt.GridBagConstraints gridBagConstraints; 

        jScrollPane1 = new javax.swing.JScrollPane();
        jListFriends = new javax.swing.JList(client.loadFollowers());
        jScrollPane3 = new javax.swing.JScrollPane();
        jTextAreaTweets = new javax.swing.JTextArea();
        jTextFieldSearch = new javax.swing.JTextField();
        jButtonSearch = new javax.swing.JButton();
        jScrollPane2 = new javax.swing.JScrollPane();
        jListSearchResult = new javax.swing.JList();
        
        // Create popup menu in order to unfollow a user
        jPopupMenuItemUnFollow = new JMenuItem();
        jPopupMenuItemUnFollow.setText("Unfollow");
        jPopupMenuUnFollow = new JPopupMenu();
        jPopupMenuUnFollow.add(jPopupMenuItemUnFollow);     
        jPopupMenuItemUnFollow.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jPopupMenuItemUnFollowActionPerformed(evt);
            }
        });
        jListFriends.setComponentPopupMenu(jPopupMenuUnFollow);
        
        // Creat popup menu in order to follow a user
        jPopupMenuItemFollow = new JMenuItem();
        jPopupMenuItemFollow.setText("Follow");
        jPopupMenuFollow = new JPopupMenu();
        jPopupMenuFollow.add(jPopupMenuItemFollow);
        jListSearchResult.setComponentPopupMenu(jPopupMenuFollow);
        jPopupMenuItemFollow.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent evt) {
				jPopupMenuItemFollowActionPerformed(evt);
			}
        });

        setMinimumSize(new java.awt.Dimension(600, 400));
        setPreferredSize(new java.awt.Dimension(600, 370));
        setLayout(new java.awt.GridBagLayout());

        jScrollPane1.setMinimumSize(new java.awt.Dimension(100, 150));
        jScrollPane1.setPreferredSize(new java.awt.Dimension(100, 150));

        jListFriends.setMaximumSize(new java.awt.Dimension(20, 80));
        jListFriends.setPreferredSize(new java.awt.Dimension(20, 50));
        jScrollPane1.setViewportView(jListFriends);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.gridheight = 2;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.ipadx = 12;
        gridBagConstraints.ipady = 107;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
        gridBagConstraints.weighty = 1.0;
        gridBagConstraints.insets = new java.awt.Insets(20, 20, 20, 20);
        add(jScrollPane1, gridBagConstraints);

        jScrollPane3.setPreferredSize(new java.awt.Dimension(500, 400));

        jTextAreaTweets.setPreferredSize(new java.awt.Dimension(500, 904));
        jScrollPane3.setViewportView(jTextAreaTweets);
        
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 2;
        gridBagConstraints.gridwidth = 3;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.ipadx = 143;
        gridBagConstraints.ipady = 73;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.weighty = 1.0;
        gridBagConstraints.insets = new java.awt.Insets(0, 20, 20, 20);
        add(jScrollPane3, gridBagConstraints);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.insets = new java.awt.Insets(20, 7, 7, 7);
        add(jTextFieldSearch, gridBagConstraints);

        jButtonSearch.setText("Search");
        jButtonSearch.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonSearchActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 2;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
        gridBagConstraints.insets = new java.awt.Insets(20, 7, 7, 20);
        add(jButtonSearch, gridBagConstraints);

        jScrollPane2.setViewportView(jListSearchResult);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.gridwidth = 2;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
        gridBagConstraints.insets = new java.awt.Insets(20, 20, 20, 20);
        add(jScrollPane2, gridBagConstraints);
    }// </editor-fold>//GEN-END:initComponents

    protected void jPopupMenuItemFollowActionPerformed(ActionEvent evt) {
		// TODO Auto-generated method stub
    	// Get the users to follow
    	if (!jListSearchResult.isSelectionEmpty()) {
    		int[] selectedUsers = jListSearchResult.getSelectedIndices();
    		for (int i=0; i < selectedUsers.length; i++) {
    			String screen_name = (String) jListSearchResult.getModel().getElementAt(selectedUsers[i]);
    			if (!client.followUser(screen_name)) {
    				JOptionPane.showMessageDialog(null, "Could not follow " + screen_name, "Error", JOptionPane.PLAIN_MESSAGE);
    			}
    		}
    	}
		
    	// Reload followed users
    	jListFriends.setListData(client.loadFollowers());
	}

	private void jPopupMenuItemUnFollowActionPerformed(ActionEvent evt) {
    	// Get the users to unfollow
    	if (!jListFriends.isSelectionEmpty()) {
    		int[] selectedUsers = jListFriends.getSelectedIndices();
    		for (int i=0; i < selectedUsers.length; i++) {
    			String screen_name = (String) jListFriends.getModel().getElementAt(selectedUsers[i]);
    			if (!client.unfollowUser(screen_name)) {
    				JOptionPane.showMessageDialog(null, "Could not unfollow " + screen_name, "Error", JOptionPane.PLAIN_MESSAGE);
    			}
    		}
    	}
    	
    	// Reload followed users
    	jListFriends.setListData(client.loadFollowers());
	}

    private void jButtonSearchActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonSearchActionPerformed
    	// Search users
    	jListSearchResult.setListData(client.getSearchResults(jTextFieldSearch.getText()));
    }//GEN-LAST:event_jButtonSearchActionPerformed


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButtonSearch;
    private javax.swing.JList jListFriends;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JTextArea jTextAreaTweets;
    private javax.swing.JTextField jTextFieldSearch;
    private javax.swing.JList jListSearchResult;
    private javax.swing.JPopupMenu jPopupMenuUnFollow;
    private javax.swing.JMenuItem jPopupMenuItemUnFollow;
    private javax.swing.JPopupMenu jPopupMenuFollow;
    private javax.swing.JMenuItem jPopupMenuItemFollow;
    // End of variables declaration//GEN-END:variables

}
